package com.miao.teacher.ui;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;

import com.espeaker.sdk.model.ReviseJson;
import com.espeaker.sdk.utils.Base64Util;
import com.miao.teacher.adapter.ReviseAudioAdapter;
import com.miao.teacher.models.AMRFile;
import com.miao.teacher.models.RecordItem;
import com.miao.teacher.models.Recorder;
import com.miao.teacher.presenters.OnInputChange;
import com.miao.teacher.presenters.OnReviseListener;
import com.miao.teacher.utils.FileUtil;
import com.miao.teacher.utils.Utils;
import com.miao.teacher.widget.SeekBarPlayer;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ListView;

public class ReviseFragment extends BaseFragment implements OnInputChange{

	public static final String SOUND_TEMP_PATH = "/tofelmiao/sound/temp/";
	public static final int SEGMENT_IGNORABLE_TIME = 100;

	private OnReviseListener mListener = null;

	private SeekBar sBar = null;
	private SeekBar revBar = null;

	private TextView curTimeTv;
	private TextView curRevTimeTv;
	private TextView totalTimeTv;
	private TextView totalRevTimeTv;
	//private Button btnPlayOrg;
	private Button btnInsertRevise;
	//private LinearLayout btnPlayRevise;

	private SeekBarPlayer ansPlayer = null;
	private SeekBarPlayer revPlayer = null;

	private boolean isReviseUpdated;
	private File answerMediaFile;
	private File reviseMediaFile;
	private ArrayList<RecordItem> recordsRevise;
	// recorder
	private Recorder reviseRecorder = null;

	ReviseAudioAdapter mAdapter = null;
	ListView lv = null;

	private ImageView imgAnim;

	private AnimationDrawable statusAnim;
	
	//private ImageView imgAnim2;

	private AnimationDrawable statusAnim2;

	private boolean mIsPlay = false;
	
	private Button btnPlay = null;
	private Button btnPre = null;
	private Button btnNext = null;
	
	private LinearLayout lly_text_input=null;
	/*
	 * 创建一个实例
	 */
	public static ReviseFragment newInstance() {
		ReviseFragment fragment = new ReviseFragment();
		return fragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.layout_my_revise, null);
		initView(view);
		return view;
	}

	private void initView(View view) {
		isReviseUpdated = false;
		imgAnim = (ImageView) view.findViewById(R.id.img_record_anim);
		imgAnim.setBackgroundResource(R.drawable.anim_revise);
		statusAnim = (AnimationDrawable) imgAnim.getBackground();
		statusAnim.start();
		
		//imgAnim2 = (ImageView) view.findViewById(R.id.img_play_anim);
		//imgAnim2.setBackgroundResource(R.drawable.anim_playing_2);
		curTimeTv = (TextView) view.findViewById(R.id.tvCurTime);
		curRevTimeTv = (TextView) view.findViewById(R.id.tvCurRevTime);
		curRevTimeTv.setVisibility(View.GONE);
		totalTimeTv = (TextView) view.findViewById(R.id.tvTotalTime);
		totalRevTimeTv = (TextView) view.findViewById(R.id.tvRevTotalTime);
		totalRevTimeTv.setVisibility(View.GONE);
		//btnPlayOrg = (Button) view.findViewById(R.id.btnPlayeOrg);
		btnInsertRevise = (Button) view.findViewById(R.id.btnInsertRevise);
		//btnPlayRevise = (LinearLayout) view.findViewById(R.id.lly_play_revise);
		sBar = (SeekBar) view.findViewById(R.id.sBar);
		revBar = (SeekBar) view.findViewById(R.id.revBar);
		revBar.setVisibility(View.GONE);
		lly_text_input=(LinearLayout) view.findViewById(R.id.lly_text_input);
		lly_text_input.setVisibility(View.GONE);
		SeekBarPlayer.setHandler(mHandler);
		sBar.postDelayed(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				ansPlayer = SeekBarPlayer.create(
						mListener.getReviseJson().audio_url, sBar, curTimeTv,
						totalTimeTv);
				ansPlayer.setOnCompletionListener(new OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer arg0) {
						mIsPlay = false;
						//ansPlayer.seekTo(0);
						//btnPlayOrg.setText("继续播放");
						btnPlay
						.setBackgroundResource(R.drawable.iv_audio_play);
					}
				});
				mAdapter.setTotlaLength(ansPlayer.getDuration());
				mAdapter.resetNewItems();
				mAdapter.notifyDataSetChanged();
			}
		}, 100);
		btnPlay = (Button) view.findViewById(R.id.btnPlayerPlay);
		btnPre = (Button) view.findViewById(R.id.btnPlayerPre);
		btnNext = (Button) view.findViewById(R.id.btnPlayerNext);
		btnPlay.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (ansPlayer != null) {
					if (ansPlayer.isReady()) {
						if (ansPlayer.isPlaying()) {
							ansPlayer.pause();
							arg0
									.setBackgroundResource(R.drawable.iv_audio_play);
						} else {
							mAdapter.DoStopAudioPlayer();
							ansPlayer.play();
							arg0
									.setBackgroundResource(R.drawable.iv_audio_pause);
							mListener.doStop(1);
						}
					}

				} else {
					arg0.setBackgroundResource(R.drawable.iv_audio_pause);
				}
			}
		});
		btnPre.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (ansPlayer == null)
					return;
				if (ansPlayer.isReady()) {
					ansPlayer.backward();
				}
			}
		});
		btnNext.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (ansPlayer == null)
					return;
				if (ansPlayer.isReady()) {
					ansPlayer.forward();
				}
			}
		});
/*		sBar.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				switch (arg1.getAction()) {
				case MotionEvent.ACTION_DOWN: 
					break;
				case MotionEvent.ACTION_UP:
					doPlayOrgAudio();
					break;
				default:
					break;
				}
				return false;
			}
		});*/
		/*btnPlayOrg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (ansPlayer == null)
					return;
				sBar.setVisibility(View.VISIBLE);
				revBar.setVisibility(View.GONE);
				curTimeTv.setVisibility(View.GONE);
				;
				curRevTimeTv.setVisibility(View.VISIBLE);
				if (ansPlayer.isReady()) {
					if (ansPlayer.isPlaying()) {
						ansPlayer.pause();
						btnPlayOrg.setText("继续播放");
					} else {
						if (reviseRecorder != null) {
							btnInsertRevise.setEnabled(true);
							
						}
						// ansPlayer.setSeekBar(sBar);
						// revPlayer.setSeekBar(null);
						ansPlayer.play();
						btnPlayOrg.setText("暂停");
					}
				}
			}
		});*/
		/*
		 * btnInsertRevise.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { // TODO Auto-generated method
		 * stub btnInsertRevise.setEnabled(false); insertReviseRecord(); } });
		 */
		btnInsertRevise.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					if (ansPlayer.isPlaying()) {
						ansPlayer.pause();
					}
					insertReviseRecord();
					imgAnim.setVisibility(View.VISIBLE);
					if (mIsPlay) {
						mIsPlay = false;
						sBar.setThumb(getActivity().getResources().getDrawable(
								R.drawable.seek_thumb_play));
					}
					btnPlay
					.setBackgroundResource(R.drawable.iv_audio_play);
					break;
				case MotionEvent.ACTION_UP:
					doStopReviseRecord();
					imgAnim.setVisibility(View.GONE);
					break;
				case MotionEvent.ACTION_CANCEL:
					doStopReviseRecord();
					imgAnim.setVisibility(View.GONE);
					break;
				}
				return false;
			}

		});
/*		btnPlayRevise.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				generateAudio();
				if (ansPlayer.isPlaying()) {
					ansPlayer.pause();
				}
				if (revPlayer != null && revPlayer.isReady()) {
					if (revPlayer.isPlaying()) {
						imgAnim2.setBackgroundResource(R.drawable.anim_playing_2);
						revPlayer.pause();
					} else {
						imgAnim2.setBackgroundResource(R.drawable.anim_gold_playing);
						statusAnim2 = (AnimationDrawable) imgAnim2.getBackground();
						statusAnim2.start();
						revPlayer.play();
					}
				}
			}
		});*/
		recordsRevise = new ArrayList<RecordItem>();
		reviseMediaFile = new File(FileUtil.SDPATH + SOUND_TEMP_PATH
				+ mListener.getReviseJson().xiaofei_id + "_revise.amr");

		for (int i = 0; i < mListener.getReviseJson().mFiles.size(); i++) {
			try {
				File temp = new File(mListener.getReviseJson().mFiles.get(i));
				if (temp.exists()) {
					RecordItem item = new RecordItem(temp);
					recordsRevise.add(item);
					item.tvDes=mListener.getReviseJson().revise_reviser_points[i].text;
				}
			} catch (Exception er) {
			}
		}
		if (recordsRevise != null && recordsRevise.size() >= 2) {
			Collections.sort(recordsRevise);
		}
		lv = (ListView) view.findViewById(R.id.lv);
		mAdapter = new ReviseAudioAdapter(getActivity(), recordsRevise,this);
		lv.setAdapter(mAdapter);
		LayoutParams lp2=lv.getLayoutParams();
		lp2.height=getYPx()/2;
		lv.setLayoutParams(lp2);
		final String mPath = FileUtil.SDPATH + SOUND_TEMP_PATH;
		final String mFileName = mListener.getReviseJson().xiaofei_id
				+ "_answer.amr";

		answerMediaFile = new File(mPath + mFileName);
		if (!answerMediaFile.exists()) {
			new Thread() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					try {
						answerMediaFile = getFileFromServer(mListener
								.getReviseJson().audio_url, mPath, mFileName);
						mAdapter.setUrl(mPath + mFileName);
					} catch (Exception er) {
					}
				}

			}.start();

		}else
		{
			mAdapter.setUrl(mPath + mFileName);
		}
	}
	private void doPlayOrgAudio()
	{
		if (ansPlayer.isReady()) {
			if (ansPlayer.isPlaying()) {
				ansPlayer.pause();
			} else {
				if (reviseRecorder != null) {
					doStopReviseRecord();
				}
				ansPlayer.play();
			}
		}
		if (mIsPlay) {
			mIsPlay = false;
			sBar.setThumb(getActivity().getResources().getDrawable(
					R.drawable.seek_thumb_play));
		} else {
			mIsPlay = true;
			sBar.setThumb(getActivity().getResources().getDrawable(
					R.drawable.seek_thumb_play));

		}
	}
	public void generateAudio() {
		if (!isReviseUpdated) {
			doStopReviseRecord();
			syncReviseSync();
		}
	}
	public void pauseAudio2() {
		try {
			if (ansPlayer != null) {
				if (ansPlayer.isPlaying()) {
					btnPlay.performClick();
				}
			}
		} catch (Exception er) {
		}
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		pauseAudio();
	}

	public void pauseAudio() {
		try {
			if (ansPlayer != null) {
				if (ansPlayer.isPlaying()) {
					ansPlayer.pause();
					ansPlayer.release();
				}
			}
			if (revPlayer != null) {
				if (revPlayer.isPlaying()) {
					revPlayer.pause();
					revPlayer.release();
				}
			}
			if (mAdapter != null) {
				mAdapter.DoStopAudioPlayer();
			}
		} catch (Exception er) {
		}
	}

	private void syncReviseSync() {
		try {
			if (recordsRevise.isEmpty()) {
				reviseMediaFile.delete();
				return;
			}
			FileOutputStream out = new FileOutputStream(reviseMediaFile);
			out.write(0X23);
			out.write(0X21);
			out.write(0X41);
			out.write(0X4D);
			out.write(0X52);
			out.write(0X0A);
			AMRFile ansAmrFile = AMRFile.create(answerMediaFile);
			int cur = 0;
			int numFrame = ansAmrFile.getNumFrames();
			for (int i = 0; i < recordsRevise.size(); ++i) {
				AMRFile recAmrFile = AMRFile.create(recordsRevise.get(i).file);
				int insertPos = recordsRevise.get(i).starttime / 20;
				if (insertPos != 0)
				{
					if(cur!=insertPos){
					out.write(ansAmrFile.getFrames(cur, insertPos));
					}
				}
				cur = insertPos;
				if(recAmrFile.getFrames().length>0)
					out.write(recAmrFile.getFrames());

			}
			if (cur != numFrame) {
				out.write(ansAmrFile.getFrames(cur, numFrame));
			}
			out.close();
			if (checkReviseFile()) {
				if (revPlayer != null)
					revPlayer.release();
				revPlayer = SeekBarPlayer.create(reviseMediaFile.toString(),
						revBar, curRevTimeTv, totalRevTimeTv);
				revPlayer.setOnCompletionListener(new OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer arg0) {
						revPlayer.seekTo(0);
					}
				});
			}
			isReviseUpdated = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void getPointArray() {
		/*
		 * if (!isReviseUpdated) { syncReviseSync(); }
		 */
		try{
		int[] revisePointSyncBase = new int[recordsRevise.size()];
		for (int i = 0; i < revisePointSyncBase.length; ++i) {
			if (i == 0) {
				revisePointSyncBase[i] = 0;
			} else {
				revisePointSyncBase[i] = revisePointSyncBase[i - 1]
						+ recordsRevise.get(i - 1).getDuration();
			}
		}
		ArrayList<ReviseJson.point> revisePointsJson = new ArrayList<ReviseJson.point>();
		for (int i = 0; i < recordsRevise.size(); ++i) {
			ReviseJson.point revisePointJson = new ReviseJson.point();
			revisePointJson.at = revisePointSyncBase[i]
					+ recordsRevise.get(i).starttime;
			revisePointJson.duration = recordsRevise.get(i).getDuration();
			revisePointJson.text=recordsRevise.get(i).tvDes==null?"":recordsRevise.get(i).tvDes;
			revisePointsJson.add(revisePointJson);
		}

		ArrayList<ReviseJson.point> reviseUserPointsJson = new ArrayList<ReviseJson.point>();
		if (recordsRevise.get(0).starttime >= SEGMENT_IGNORABLE_TIME) {
			ReviseJson.point userJson = new ReviseJson.point();
			userJson.at = 0;
			userJson.duration = recordsRevise.get(0).starttime;
			reviseUserPointsJson.add(userJson);
		}
		for (int i = 0; i < recordsRevise.size() - 1; ++i) {
			ReviseJson.point userJson = new ReviseJson.point();
			userJson.at = revisePointSyncBase[i]
					+ recordsRevise.get(i).starttime
					+ recordsRevise.get(i).getDuration();
			userJson.duration = revisePointSyncBase[i + 1]
					+ recordsRevise.get(i + 1).starttime
					- (revisePointSyncBase[i] + recordsRevise.get(i).starttime + recordsRevise
							.get(i).getDuration());
			reviseUserPointsJson.add(userJson);
		}
		if (recordsRevise.get(recordsRevise.size() - 1).starttime
				+ SEGMENT_IGNORABLE_TIME <= ansPlayer.getDuration()) {
			ReviseJson.point userJson = new ReviseJson.point();
			userJson.at = revisePointSyncBase[recordsRevise.size() - 1]
					+ recordsRevise.get(recordsRevise.size() - 1).starttime
					+ recordsRevise.get(recordsRevise.size() - 1).getDuration();
			userJson.duration = revPlayer.getDuration()
					- (revisePointSyncBase[recordsRevise.size() - 1]
							+ recordsRevise.get(recordsRevise.size() - 1).starttime + recordsRevise
							.get(recordsRevise.size() - 1).getDuration());
			reviseUserPointsJson.add(userJson);
		}
		mListener.getReviseJson().revise_reviser_points = new ReviseJson.point[revisePointsJson
				.size()];
		for (int i = 0; i < revisePointsJson.size(); i++) {
			mListener.getReviseJson().revise_reviser_points[i] = revisePointsJson
					.get(i);
		}
		mListener.getReviseJson().revise_user_points = new ReviseJson.point[reviseUserPointsJson
				.size()];
		for (int i = 0; i < reviseUserPointsJson.size(); i++) {
			mListener.getReviseJson().revise_user_points[i] = reviseUserPointsJson
					.get(i);
		}
		byte[] mBytes = com.miao.teacher.utils.ConvertUtils
				.getBytesFromFile(reviseMediaFile);
		mListener.getReviseJson().revise_audio = Base64Util.encodeStr(mBytes);
		
		mListener.doSave();
		}catch(Exception er)
		{}
	}

	private boolean checkReviseFile() {
		boolean re = reviseMediaFile.exists();
		return re;
	}

	private File getFileFromServer(String remoteUrl, String path,
			String fielname) throws Exception {
		// 如果相等的话表示当前的sdcard挂载在手机上的并且是可用的
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			URL url = new URL(remoteUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			// 获取文件的大小
			// String totalSize = bytes2kb(conn.getContentLength());

			// pd.setMax(conn.getContentLength());
			InputStream is = conn.getInputStream();
			File file = new File(path, fielname);
			FileOutputStream fos = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024];
			int len;
			int total = 0;
			while ((len = bis.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
				total += len;
			}
			fos.close();
			bis.close();
			is.close();
			return file;
		} else {
			return null;
		}
	}

	private void doStopReviseRecord() {
		if (reviseRecorder != null) {
			reviseRecorder.stop();
			reviseRecorder.release();
			RecordItem item=new RecordItem(reviseRecorder.getFile());
			recordsRevise.add(item);
			reviseRecorder = null;
			System.gc();
			Collections.sort(recordsRevise);
			mAdapter.resetNewItems();
			mAdapter.notifyDataSetChanged();
			isReviseUpdated = false;
		}
	}

	private boolean insertReviseRecord() {

		if (reviseRecorder != null) {
			// get the file name and refresh the listview, always add
			doStopReviseRecord();
			return false;
		} else {
			if (!Utils.isExternalStorageWritable()) {
				return false;
			}
			String mPath = FileUtil.SDPATH + SOUND_TEMP_PATH;
			File APath = new File(mPath);
			if (!APath.exists()) {
				FileUtil.DoCreateDir(mPath);
			}
			String tempRecordFile = mPath + "temp_rev_"
					+ mListener.getReviseJson().xiaofei_id + "_"
					+ ansPlayer.getCurrentPosition() + "_rev.amr";
			mListener.getReviseJson().mFiles.add(tempRecordFile);
			File tempFile = new File(tempRecordFile);
			if (tempFile.exists()) {
				for (int i = 0; i < recordsRevise.size(); ++i) {
					if (recordsRevise.get(i).starttime == ansPlayer
							.getCurrentPosition()) {
						recordsRevise.remove(i);
						break;
					}
				}
			}
			reviseRecorder = Recorder.create(tempFile);
			if (reviseRecorder != null) {
				reviseRecorder.start();
				return true;
			}
		}
		return false;
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		try {
			mListener = (OnReviseListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ "must implement OnReviseListener");
		}
	}

	@Override
	public void showInput(final RecordItem item) {
		// TODO Auto-generated method stub
		lly_text_input.setVisibility(View.VISIBLE);
		btnInsertRevise.setVisibility(View.GONE);
		final EditText edt=(EditText)lly_text_input.findViewById(R.id.edt_des);
		edt.requestFocus();
		final Button btn=(Button)lly_text_input.findViewById(R.id.btnSend);
		btn.setText("取消");
		btn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(btn.getText().toString().equals("取消"))
				{
					lly_text_input.setVisibility(View.GONE);
					btnInsertRevise.setVisibility(View.VISIBLE);
					mAdapter.notifyDataSetChanged();
				}else
				{
					item.tvDes=edt.getText().toString();
					mAdapter.notifyDataSetChanged();
					lly_text_input.setVisibility(View.GONE);
					btnInsertRevise.setVisibility(View.VISIBLE);
					edt.setText("");
				}
			}
			
		});
		edt.addTextChangedListener(new TextWatcher(){
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if(edt.getText().toString().length()==0)
				{
					btn.setText("取消");
				}else
				{
					btn.setText("发送");
				}
			}
			
		});
	}

	@Override
	public void stopAudio() {
		// TODO Auto-generated method stub
		if (ansPlayer!=null&&ansPlayer.isPlaying()) {
			btnPlay.performClick();
		}
	}
}
